package com.talent.proxy.mysql.common.packets.s2c.resultset;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.talent.aio.common.ChannelContext;
import com.talent.proxy.mysql.common.MysqlExt;
import com.talent.proxy.mysql.common.MysqlPacket;
import com.talent.proxy.mysql.common.MysqlReturn;
import com.talent.proxy.mysql.common.utils.BufferUtil;

/**
 * 
 * <pre><b>resultset row packet.</b></pre>
 * @author 
 * <pre>seaboat</pre>
 * <pre><b>email: </b>849586227@qq.com</pre>
 * <pre><b>blog: </b>http://blog.csdn.net/wangyangzhizhou</pre>
 * @version 1.0
 * @see http://dev.mysql.com/doc/internals/en/com-query-response.html#text-resultset
 */
public class RowDataPacket extends MysqlPacket
{
	private static Logger log = LoggerFactory.getLogger(BufferUtil.class);
	private static final byte NULL_MARK = (byte) 251;
	public int columnCount;
	public List<byte[]> valueBytes = new ArrayList<>();
	public List<Object> values = new ArrayList<>();

	//	public RowDataPacket()
	//	{
	//
	//	}

	public boolean isCompletePacket()
	{
		return false;
	}
	
	public RowDataPacket(int columnCount)
	{
		this.columnCount = columnCount;
	}

	@Override
	public void decodeBody(ByteBuffer buffer, ChannelContext<MysqlExt, MysqlPacket, MysqlReturn> channelContext)
	{
		for (int i = 0; i < columnCount; i++)
		{
			byte[] bs = BufferUtil.readBytesWithLength(buffer);
			valueBytes.add(bs);//.readBytesWithLength()
			if (bs != null)
			{
				try
				{
					values.add(new String(bs));
				} catch (Exception e)
				{
					log.error(e.toString(), e);
				}
			}

		}
	}

	@Override
	public ByteBuffer encode(ChannelContext<MysqlExt, MysqlPacket, MysqlReturn> channelContext)
	{
		int bodySize = bodySize();
		ByteBuffer buffer = ByteBuffer.allocate(HEADER_SIZE + bodySize);
		BufferUtil.writeUB3(buffer, bodySize);
		buffer.put(seqId);
		for (int i = 0; i < columnCount; i++)
		{
			byte[] fv = valueBytes.get(i);
			if (fv == null)
			{
				buffer.put(NULL_MARK);
			} else
			{
				BufferUtil.writeLength(buffer, fv.length);
				buffer.put(fv);
			}
		}
		return buffer;
	}

	@Override
	public int bodySize()
	{
		int size = 0;
		for (int i = 0; i < columnCount; i++)
		{
			byte[] v = valueBytes.get(i);
			size += (v == null || v.length == 0) ? 1 : BufferUtil.getLength(v);
		}
		return size;
	}

	@Override
	protected String packetDesc()
	{
		return "MySQL Resultset Row Packet";
	}

	/** 
	 * @see com.talent.proxy.mysql.common.MysqlPacket#onReceived(com.talent.aio.common.ChannelContext)
	 * 
	 * @param channelContext
	 * @return
	 * @重写人: tanyaowu
	 * @重写时间: 2017年1月23日 下午5:00:07
	 * 
	 */
	@Override
	public MysqlReturn onReceived(ChannelContext<MysqlExt, MysqlPacket, MysqlReturn> channelContext)
	{
		// TODO Auto-generated method stub
		return null;
	}

}
